package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java1234.entity.*;
import com.java1234.util.LogUtil;
import com.java1234.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import com.java1234.service.LuntancategoryService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 论坛帖子分类
 */
@RestController
@RequestMapping("/bsns/luntan/categorys")
public class LunTanCategoryController {

    @Autowired
    private LuntancategoryService lunTanCategoryService;
    @Autowired
    private LogUtil logUtil;
    @Autowired
    private HttpServletRequest request;

    /**
    *分页查询帖子分类列表(后台)
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @param query 查询条件
     * @return 帖子分类分页数据
     */
    @GetMapping("/selectPage")
    public ResponseEntity<R> getCategoryPage(@RequestParam(defaultValue = "1") int pageNum,
                                             @RequestParam(defaultValue = "10") int pageSize,
                                             @RequestParam(required = false) String query) {
        try {
            // 创建分页对象
            Page<Luntancategory> page = new Page<>(pageNum, pageSize);
            // 创建查询条件包装器
            QueryWrapper<Luntancategory> queryWrapper = new QueryWrapper<>();
            if (query!= null &&!query.isEmpty()) {
                // 根据具体的查询需求添加条件，这里以帖子分类名称进行模糊查询为例
                queryWrapper.like("name", query);
                // 你也可以添加更多的查询条件，比如根据备注字段模糊查询等
                // queryWrapper.or().like("remark", query);
            }
            // 调用服务层方法，传入分页对象和查询条件包装器
            page = lunTanCategoryService.getCategoryPage(page, queryWrapper);

            R r = R.ok();
            r.put("page", page);
            // 记录日志
            logUtil.logOperation(request, "分页查询帖子分类列表", "getCategoryPage", query, r.toString());
            return new ResponseEntity<>(r, HttpStatus.OK);
        } catch (Exception e) {
            // 记录异常日志
            logUtil.logOperation(request, "分页查询帖子分类列表", "getCategoryPage", query, "异常: " + e.getMessage());
            return new ResponseEntity<>(R.error("分页查询帖子分类列表出现异常"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
    * 查询所有帖子分类列表（前台）
     * @return 所有帖子分类列表
     */
    @GetMapping("/selectAll")
    public ResponseEntity<List<Luntancategory>> getAllCategory() {
        List<Luntancategory> categories = lunTanCategoryService.getAllCategory();
        // 记录日志
        logUtil.logOperation(request, "查询所有帖子分类列表", "getAllCategory", "", categories.toString());
        return new ResponseEntity<>(categories, HttpStatus.OK);
    }

    /**
    * 根据ID查询帖子分类详情
     * @param id 帖子分类ID
     * @return 帖子分类详情
     */
    @GetMapping("/selectById/{id}")
    public ResponseEntity<Luntancategory> getCategoryById(@PathVariable Integer id) {
        Luntancategory category = lunTanCategoryService.getCategoryById(id);
        // 记录日志
        logUtil.logOperation(request, "根据ID查询帖子分类详情", "getCategoryById", "id=" + id, category != null ? category.toString() : "未找到");
        if (category!= null) {
            return new ResponseEntity<>(category, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    /**
    * 新增帖子分类Controller
     * @param category 帖子分类信息
     * @return 新增结果
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addCategory(@Validated @RequestBody Luntancategory category) {
        // 检查分类是否已经存在
        QueryWrapper<Luntancategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", category.getName());
        Luntancategory existingCategory = lunTanCategoryService.getOne(queryWrapper);

        if (existingCategory != null) {
            // 分类已经存在，返回提示信息
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "分类已存在，请勿重复添加");
            // 记录日志
            logUtil.logOperation(request, "新增帖子分类", "addCategory", category.toString(), "分类已存在");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        // 分类不存在，执行新增操作
        boolean result = lunTanCategoryService.addCategory(category);
        if (result) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "分类添加成功");
            // 记录日志
            logUtil.logOperation(request, "新增帖子分类", "addCategory", category.toString(), "分类添加成功");
            return new ResponseEntity<>(response, HttpStatus.CREATED);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "分类添加失败，请稍后重试");
            // 记录日志
            logUtil.logOperation(request, "新增帖子分类", "addCategory", category.toString(), "分类添加失败");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
    * 根据ID删除帖子分类
     *  @param id 帖子分类ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Boolean> deleteCategoryById(@PathVariable Integer id) {
        boolean result = lunTanCategoryService.deleteCategoryById(id);
        // 记录日志
        logUtil.logOperation(request, "根据ID删除帖子分类", "deleteCategoryById", "id=" + id, result ? "删除成功" : "删除失败");
        if (result) {
            return new ResponseEntity<>(true, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        lunTanCategoryService.removeByIds(Arrays.asList(ids));
        // 记录日志
        logUtil.logOperation(request, "删除帖子分类", "delete", "ids=" + Arrays.toString(ids), "删除成功");
        return R.ok();
    }

    /**
    *批量删除帖子分类
     *  @param ids 帖子分类ID列表
     * @return 删除结果
     */
    @DeleteMapping("/delete/batch")
    public ResponseEntity<Boolean> deleteCategoriesByIds(@RequestBody List<Integer> ids) {
        boolean result = lunTanCategoryService.deleteCategoriesByIds(ids);
        // 记录日志
        logUtil.logOperation(request, "批量删除帖子分类", "deleteCategoriesByIds", "ids=" + ids.toString(), result ? "删除成功" : "删除失败");

        if (result) {
            return new ResponseEntity<>(true, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
    *更新帖子分类信息
     *  @param category 帖子分类信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<Boolean> updateCategory(@Validated @RequestBody Luntancategory category) {
        boolean result = lunTanCategoryService.updateCategory(category);
        // 记录日志
        logUtil.logOperation(request, "更新帖子分类信息", "updateCategory", category.toString(), result ? "更新成功" : "更新失败");
        if (result) {
            return new ResponseEntity<>(true, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
    * 保存帖子分类信息
     *  @param category 帖子分类信息
     * @return 保存结果
     */
    @PostMapping("/save")
    public R save(@RequestBody Luntancategory category) {
        // 检查分类是否已经存在
        QueryWrapper<Luntancategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", category.getName());
        Luntancategory existingCategory = lunTanCategoryService.getOne(queryWrapper);

        if (category.getId() == null || category.getId() == -1) {
            // 新增分类
            if (existingCategory != null) {
                // 分类已经存在，返回提示信息
                // 分类已经存在，返回提示信息
                logUtil.logOperation(request, "保存帖子分类信息", "save", category.toString(), "分类已存在");
                return R.error("分类已存在，请勿重复添加");
            }
            category.setCreateTime(new Date());
            lunTanCategoryService.save(category);
            logUtil.logOperation(request, "保存帖子分类信息", "save", category.toString(), "新增成功");
        } else {
            // 更新分类
            if (existingCategory != null && !existingCategory.getId().equals(category.getId())) {
                // 分类已经存在，且不是当前分类，返回提示信息
                logUtil.logOperation(request, "保存帖子分类信息", "save", category.toString(), "分类已存在");
                return R.error("分类已存在，请勿重复添加");
            }
            lunTanCategoryService.updateById(category);
            logUtil.logOperation(request, "保存帖子分类信息", "save", category.toString(), "更新成功");
        }
        return R.ok();
    }
}